package com.handsure.xixili.controller;


import com.handsure.xixili.entity.Employee;
import com.handsure.xixili.handler.Response;
import com.handsure.xixili.repository.EmployeeRepository;
import com.handsure.xixili.util.BaseTools;
import com.handsure.xixili.util.PrimaryKey;
import com.handsure.xixili.util.SHA1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Arvin.Cao
 * @version 1.0
 * @time 16/6/17 下午3:04
 * @Description TODO
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeRepository employeeRepository;

    /**
     * 保存后台用户
     *
     * @param employee
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity saveEmployee(@RequestBody Employee employee) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee e = employeeRepository.findByUsernameAndRemoved(employee.getUsername(),0);
            if (e == null) {
                e = new Employee();
                e.setUpdateTime(BigInteger.valueOf(BaseTools.systemtimeLong()));
                e.setCreateTime(BigInteger.valueOf(BaseTools.systemtimeLong()));
                e.setUsername(employee.getUsername());
                e.setNickname(employee.getNickname());
                e.setPassword(SHA1.getDigestOfString(employee.getPassword()));
                e.setPhone(employee.getPhone());
                e.setRealname(employee.getRealname());
                e.setId(PrimaryKey.get().toString());
                e.setRemoved(0);
                employeeRepository.save(e);

                data.put("sucflag", true);
            } else {
                data.put("sucflag", false);
                data.put("message", "该登录名已被注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }

        return Response.success(data);
    }

    /**
     * 分页查询用户信息
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity findEmployee(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> data = new HashMap<>();
        try {
            Page<Employee> employees = employeeRepository.findByRemoved(0, new PageRequest(page, size, new Sort(Sort.Direction.DESC, "updateTime")));
            return Response.success(employees);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
    }

    /**
     * 根据ID获取后台用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity getEmployee(@PathVariable String id) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee e = employeeRepository.findOne(id);
            if (e != null) {
                data.put("sucflag", true);
                data.put("employee", e);
            } else {
                data.put("sucflag", false);
                data.put("message", "对不起,该用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteEmployee(@PathVariable String id) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee employee = employeeRepository.findOne(id);
            if (employee != null) {
                employee.setRemoved(1);
                employeeRepository.save(employee);
                data.put("sucflag", true);
                data.put("message", "删除成功");
            } else {
                data.put("sucflag", false);
                data.put("message", "对不起,该用户不存在,无法删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);

    }

    /**
     * 更新用户
     *
     * @param employee
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity updateEmployee(@RequestBody Employee employee) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee emp = employeeRepository.findOne(employee.getId());
            if (emp != null) {
                emp.setUpdateTime(BigInteger.valueOf(BaseTools.systemtimeLong()));
                emp.setRealname(employee.getRealname());
                emp.setUsername(employee.getUsername());
                emp.setPhone(employee.getPhone());
                emp.setNickname(employee.getNickname());
                employeeRepository.save(emp);
                data.put("sucflag", true);
                data.put("message", "更新成功");
            } else {
                data.put("sucflag", false);
                data.put("message", "对不起,该用户不存在,无法进行更新");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/reset/{id}", method = RequestMethod.PUT)
    public ResponseEntity resetPassword(@PathVariable String id) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee employee = employeeRepository.findOne(id);
            if (employee != null) {
                employee.setPassword(SHA1.getDigestOfString("123456"));
                employeeRepository.save(employee);
                data.put("sucflag", true);
                data.put("message", "重置密码成功");
            } else {
                data.put("sucflag", false);
                data.put("message", "对不起,该用户不存在,无法进行重置密码");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }

    /**
     * 后台用户登录
     *
     * @param employee
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity login(HttpSession session, @RequestBody Employee employee) {
        Map<String, Object> data = new HashMap<>();
        try {
            Employee e = employeeRepository.findByUsernameAndRemoved(employee.getUsername(),0);
            if (e != null && e.getPassword().equals(SHA1.getDigestOfString(employee.getPassword()))) {
                session.setAttribute("employee", e.getId());
                data.put("sucflag", true);
                data.put("message", "登录成功");
            } else {
                data.put("sucflag", false);
                data.put("message", "登录失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }

    /**
     * 信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ResponseEntity info(HttpSession session) {
        Map<String, Object> data = new HashMap<>();
        try {
            String id = (String) session.getAttribute("employee");
            Employee e = employeeRepository.findOne(id);
            data.put("sucflag", false);
            data.put("realname", e.getRealname());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ResponseEntity logout(HttpSession session) {
        Map<String, Object> data = new HashMap<>();
        try {
            session.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError("对不起,服务器出了点问题");
        }
        return Response.success(data);
    }

}
